package com.price.sample.http.interceptor

import androidx.constraintlayout.motion.widget.TransitionBuilder.validate
import com.price.common.extend.logDebug
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject

/**
 * Created by admin
 * Description: 自己解析错误信息,并构造成标准json格式 body就是后台返回的json 改变返回数据
 * PS:  怎么解析根据自己业务来,我是解析我后台给我的错误数据....
 */
class MyResponseInterceptor: ResponseBodyInterceptor() {
    override fun intercept(response: Response, url: String?, body: String?): Response {
        kotlin.runCatching {
            //只有注册时需要了
            if (url!!.contains("CICRegService.asmx")) {
                var msg: String? = response.message
                val jsonObject = JSONObject()
                jsonObject.put("code", response.code + 1000)
                jsonObject.put("msg", msg)

                    jsonObject.put("data", body)
                    msg = body

                logDebug("Interceptor---攔截返回:\n$jsonObject", null)
                val mediaType: MediaType? = "application/json;charset=utf-8".toMediaTypeOrNull()
                val newBody = jsonObject.toString().toResponseBody(mediaType)
                return response.newBuilder()
                    .message(msg!!)
                    .body(newBody).build()
            }
        }
        return response
    }
}